#!/usr/bin/env python

# Add conf file reader 

import sys

import curses 
import curses.wrapper #not being used right now

from twisted.internet import reactor
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import LineReceiver
from twisted.python import log

from Putter import Window, Client, Factory

class PutterMain:
    def __init__(self, stdscr):
        self.stdscr = stdscr
        self.stdscr.nodelay(1)
        self.stdscr.keypad(1)

        curses.noecho()
        curses.cbreak()
        curses.curs_set(0)

        self.__initWindows__()

    def close(self):
        curses.nocbreak()
        self.stdscr.keypad(0)
        curses.echo()
        curses.endwin()

    def __initWindows__(self):
        self.rows, self.cols = self.stdscr.getmaxyx() 

        self.chatArea  = Window(self.rows-3, self.cols-25, 0, 0 , self)
        self.buddyArea = Window(self.rows-3, 25,0, self.cols-25, self)
        self.entryArea = Window(3, self.cols, self.rows-3,0  ,self)

        self.chatArea.setNextFocus(self.buddyArea)
        self.buddyArea.setNextFocus(self.entryArea)
        self.entryArea.setNextFocus(self.chatArea)

        self.entryArea.setFocus(True)

        self.buddyArea.addLine("1) stevek")
        self.buddyArea.addLine("2) sab (Eating lunch)")
        self.entryArea.addLine("hello")

        self.redraw()

    # Inherited
    def logPrefix(self):
        return "Putter"

    # Inherited
    def fileno(self):
        """ select FD 0 """
        return 0

    # Inherited
    def connectionLost(self, reason):
        # make screen go red or something
        pass

    # Inherited
    def doRead(self):
        c = self.stdscr.getch()
        if c == 27: # ESC
            reactor.stop()
        else:
            self.focusedArea.keyRead(c)

    def redraw(self):
        self.rows, self.cols = self.stdscr.getmaxyx() 
        self.stdscr.refresh()
        self.chatArea.refresh()
        self.buddyArea.refresh()
        self.entryArea.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    pwindow = PutterMain(stdscr)
    factory = Factory(pwindow)
    reactor.addReader(pwindow)
    reactor.connectTCP("localhost",1025,factory)
    reactor.run()
    pwindow.close()
